27. Gson

Gson 的使用

对象和 json 字符串的相互转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.itguigu.demo;

import org.junit.jupiter.api.Test;

import com.google.gson.Gson;
import com.itguigu.bean.Student;

public class Demo {
@Test
public void testJsonStrObject() {
Gson gson = new Gson();
// 将 student 转换为 json 格式字符串
Student student = new Student("zhangsan", 20);
String json = gson.toJson(student);
System.out.println(json); // {"name":"zhangsan","age":20}

// 将 json 字符串转换为对象
Student student2 = gson.fromJson(json, Student.class);
System.out.println(student2); // Student [name=zhangsan, age=20]
}
}

带泛型的 List。因为有了泛型,所以我们在使用 fromJson 的时候就不能使用上面的那种方式了,而是要使用 TypeToke,将类型传递进去,然后通过 getType 获取类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
public void testJsonStrList() {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("lisi", 24));
students.add(new Student("wangwu", 88));
students.add(new Student("zhaoliu", 99));

Gson gson = new Gson();
String json = gson.toJson(students);
System.out.println(json);
// [{"name":"lisi","age":24},{"name":"wangwu","age":88},{"name":"zhaoliu","age":99}]

// 下面这种使用方式有问题,只能转换外层的 ArrayList,里面不是 Student
// ArrayList<Student> arrayList = gson.fromJson(json, ArrayList.class);
// System.out.println(arrayList.get(0));

// 使用 typeToken 的方式。直接传入我们需要的集合的泛型 ArrayList<Student>,然后获取类型即可
ArrayList<Student> students2 = gson.fromJson(json, new TypeToken<ArrayList<Student>>() {}.getType());
System.out.println(students2.get(0));
System.out.println(students2.get(0).getName());
}

带泛型的 Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testJsonStrMap() {
HashMap<String, Student> map = new HashMap<>();
map.put("zhangsan", new Student("zhangsan", 99));
map.put("lisi", new Student("lisi", 44));

Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);
// {"lisi":{"name":"lisi","age":44},"zhangsan":{"name":"zhangsan","age":99}}

HashMap<String, Student> map2 = gson.fromJson(json, new TypeToken<HashMap<String, Student>>() {}.getType());
System.out.println(map2);
System.out.println(map2.get("lisi"));
System.out.println(map2.get("lisi").getAge());
}